package com.lhn.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ServiceConfigurationError;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * bio demo
 *
 * @author lhn
 * @date 2025/05/25 17:09
 * @since 1.0.0
 **/
public class BIOService {

    public static void main(String[] args) throws IOException {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 创建 ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务启动了");
        while (true) {
            // 监听
            System.out.println(Thread.currentThread().getId() + "=====" + Thread.currentThread().getName());
            System.out.println("等待连接.....");
            final Socket accept = serverSocket.accept();
            System.out.println("连接到一个客户端");
            executorService.execute(() -> {
                // 可以和客户端通信
                handler(accept);
            });
        }
    }


    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        System.out.println(Thread.currentThread().getId() + "=====" + Thread.currentThread().getName());
        try {
            // socket 获取到一个输入流
            System.out.println("waiting read....");
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            System.out.println("关闭client 连接");
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}